const strFormat = require("../../util/strFormat");
const sql = (start, length) => {
  return strFormat(
    "select a.id, a.name, c.id as stationid, c.name as stationname, b.sequence, c.waitingnumber " + 
    "from line as a " + 
    "left join stationinline as b " + 
    "on a.id=b.lineid " + 
    "left join station as c " +
    "on b.stationid=c.id " + 
    "order by a.id, b.sequence " +  
    "limit {start},{length};",
    { start: start, length: length }
  );
};

const getlineinfo = (connection, req, res) => {
  const start = parseInt(req.query.start) || 0;
  const length = parseInt(req.query.length) || 1000;

  connection.query(sql(start, length), (err, result) => {
    var data = null;

    if ( err ) {
      console.error(err);
      res.status(200).json({
        status: "fail",
        data: data,
      });
      return;
    } else {
      data = [];
      var index = [];

      result.forEach(item => {
        var key = 0;
        data.forEach(group => {
          if ( item.id === group.id ) 
            key = 1;
        });

        if ( key === 0 ) {
          data.push({
            id: item.id,
            name: item.name,
            station: [],
          });
          index[item.id] = 0;
        }
      });

      result.forEach(item => {
        data.forEach(group => {
          if ( item.id === group.id ) {
            group.station.push({
              stationid: item.stationid,
              stationname: item.stationname,
              sequence: item.sequence,
              index: index[item.id],
              waitingnumber: item.waitingnumber,
            });
            index[item.id] += 1;
          }
        });
      });

      res.status(200).json({
        status: "success",
        data: data,
      });
    }
  });
}

module.exports = getlineinfo;